﻿
#if WINDOWS

using System.Windows.Threading;

#else

using Avalonia.Threading;

#endif

namespace KinonekoSoftware.Foundation.UI.ViewModels
{


    public abstract class DialogCountable : DialogBase
    {
        private int             _remain;
        private DispatcherTimer _timer;
        
        
        protected override void OnStart()
        {
            if (EnableCountDown)
            {
                OnSetCountDownText(false);
                Remain = CountDown;
                _timer = new DispatcherTimer(DispatcherPriority.Normal)
                {
                    Interval = TimeSpan.FromSeconds(1),
                };
                
                _timer.Tick += OnCountDown;
                _timer.Start();
            }
            base.OnStart();
        }
        
        
        internal virtual void OnSetCountDownText(bool isFinish){}
        
        
        private void OnCountDown(object sender, EventArgs e)
        {
            Remain--;

            if (Remain <= 0)
            {
                _timer.Tick -= OnCountDown;
                _timer.Stop();
                OnSetCountDownText(true);
                CanFinish();
            }
            else
            {
                OnSetCountDownText(false);
            }
        }
        
        /// <summary>
        /// 是否开启倒计时
        /// </summary>
        public bool EnableCountDown { get; init; }
        
        /// <summary>
        /// 倒计时的时间，单位：秒
        /// </summary>
        public int CountDown { get; init; }

        /// <summary>
        /// 获取或设置 <see cref="Remain"/> 属性。
        /// </summary>
        public int Remain
        {
            get => _remain;
            protected set => SetValue(ref _remain, value);
        }
    }
}